package com.sy.controller;

import com.sy.dto.JsonResult;
import com.sy.utils.RandomUtils;
import com.sy.utils.SMSUtils;
import com.sy.utils.SmsCodeUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import static com.sy.constant.BusinessConstant.SESSION_VALIDATE_CODE;
import static com.sy.constant.BusinessConstant.VALIDATE_CODE_LENGTH;

/**
 * 用于动态绘制图形验证码
 */
@RestController
@RequestMapping("validateCode")
public class ValidateCodeController {
    @RequestMapping("getValidateCode")
    protected void generateValidateCode(HttpSession session,HttpServletResponse resp) throws ServletException, IOException {
        String code = RandomUtils.generateValidateCode(VALIDATE_CODE_LENGTH);
        //将生成的验证码存入Session中，后续用户在操作的时候输入的验指码要和它进行比较
        session.setAttribute(SESSION_VALIDATE_CODE, code);
        BufferedImage image = RandomUtils.drawValidateCode(code);
        try {
            //设置消息头为输出图片类型
            resp.setContentType("image/png");
            OutputStream os = resp.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("sendNumber")
    public JsonResult SendNumber(HttpSession session,String number){
        String randomString = SmsCodeUtils.getRandomString(4);
        session.setAttribute("number",randomString);
        System.out.println(randomString);
        SMSUtils.run(number,randomString);
        JsonResult jsonResult = new JsonResult();
        return jsonResult.setData(randomString).setCode(200);
    }
}
